<script>
	import {
		checkUpdater
	} from '@/utils/checkUpdater';
	import {
		mapMutations,
		mapState
	} from 'vuex';
	import url_config from "@/common/config.js";
	export default {
		data() {
			return {
				jyJPush: [],
				baGray: {}
			};
		},
		onLaunch: function() {
			console.log('-------进入------')
			// const client = plus.push.getClientInfo();
			// 	console.log('当前设备ID', client.clientid)
			//#ifdef APP-PLUS
			//plus.runtime.setBadgeNumber(9);
			// plus.screen.lockOrientation('portrait-primary');
			//----极光推送开始
			this.jyJPush = uni.requireNativePlugin('JY-JPush'); //测试需要注释
			//安卓需要单独初始化（方便上架应用宝等有高要求的应用市场）
			// this.jyJPush.android_init(res=> {
			// 	uni.showToast({
			// 		icon:'none',
			// 		title: JSON.stringify(result)
			// 	})
			// })
			//  返回的数据会有registrationID，errorCode
			this.jyJPush.getRegistrationID(result => { //测试需要注释
				// uni.showToast({
				// 	icon: 'none',
				// 	title: JSON.stringify(result)
				// })
				console.log('registrationId========', JSON.stringify(result))
				this.notice(result)
			});
			console.log('---进入----001')
			this.jyJPush.setJYJPushAlias({ //测试需要注释
					userAlias: 'testAlias'
				},
				result => {
					// console.log(result,'--002--');
					//  设置成功或者失败，都会通过这个result回调返回数据；数据格式保持极光返回的安卓/iOS数据一致
					//  注：若没有返回任何数据，考虑是否初始化完成
					// uni.showToast({
					//  icon: 'none',
					//  title: JSON.stringify(result),
					//  duration: 7000
					// });
					//点击推送到达指定页面
					// uni.navigateTo({
					// 	url: '/pages/authentication/authentication'
					// })
				}
			);
			console.log('-----------003')
			this.jyJPush.addJYJPushReceiveNotificationListener(result => { //测试需要注释
				plus.device.vibrate(2000);
				//自定义铃声
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://admin.515f.com/static/media/tx.e3598bf6.mp3';
				innerAudioContext.onPlay(() => {
					console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				setTimeout(() => {
					innerAudioContext.destroy()
				}, 15000)
			});
			this.jyJPush.addJYJPushReceiveOpenNotificationListener(result => { //测试需要注释
				// 监听成功后， 若点击推送消息， 会触发result； 数据格式保持极光返回的安卓 / iOS数据一致
				// uni.showToast({
				// 	icon: 'none',
				// 	title: JSON.stringify(result.notificationContent)
				// });
			});

			//#endif
			// app打开时先检查是否有更新记录（更新记录会被保存在storage中）
			// 更新记录的内容为 { 更新标记, 安装包位置 }
			// 如果存在更新记录，且更新标记（complete=true）则删除上次使用过的安装包，达到存储释放空间的目的
			// 如果存在更新记录，且更新标记（complete=false）则进行安装更新 - 2019年3月27日 新增强制更新内容
			//#ifdef APP-PLUS
			plus.screen.lockOrientation('portrait-primary') //竖屏正方向锁定
			checkUpdater()
			//#endif
			setTimeout(() => {
				//#ifdef APP-PLUS
				plus.navigator.closeSplashscreen();
				//#endif
			}, 3000);
			if (uni.getStorageSync("uuid")) {
				uni.switchTab({
					url: "/pages/index/index"
				});
				// uni.navigateTo({
				// 	url:"/pages/login/login"
				// })
			}
			//极光推送


			// //获取h5跳转app携带的参数
			// var geturl = `zhuyewang://zhuyeapp.com/newIndex?id=194&onwerVote=0`
			// let getqyinfo = geturl.split('?')[1];////获取后边的字符串
			// console.log(getqyinfo,'+++++++++++字符串++++++++++++++')
			// let getqys = getqyinfo.split('&')
			// console.log(getqys,'*******************')
			// let obj = {}  //创建空对象，接收截取的参数
			// for(let i = 0;i < getqys.length;i++ ){
			//     console.log(i)
			//     let item = getqys[i].split('=')
			//     let key = item[0]
			//     let value = item[1]
			//     obj[key] = value 
			// }
			// // console.log(obj)
			// uni.setStorageSync('firstVote',obj)
			// console.log(obj)





		},

		onShow: function() {

			// #ifdef APP-PLUS
			// plus.runtime.setBadgeNumber(19);
			this.$request.api.messageList({
				room_id: uni.getStorageSync('projectItem').roomId,
				user_id: uni.getStorageSync('rawData').userId,
				proId: uni.getStorageSync('projectItem').proId,
				notice_type: '业主端',
				roomNumber: uni.getStorageSync('myPosition')
			}).then(res => {
				console.log('setBadgeNumber=========', res.data.data)
				if (res && res.data) {
					plus.runtime.setBadgeNumber(res.data.data.allRedTotal)
				}

			})
			//#endif
			console.log('App Show');


			// 开启通信通道(用于监听，调接口)
			this.creatSocket()


			// console.log('唤醒app------------：', window.location.href)

			// this.setBgGray(); //全局设置背景颜色为灰色
		},
		onMounted: function() {

			let obj = [1, 2, 3, 4, 5]
			let a = obj.toString()
			let index = a
			console.log(index)

		},
		// onMounted: function(){
		// 	console.log('App Show','++++++++++++++++++++++++++++++++++++++++++++++++++');
		// 	if(window.location.href == ''){
		// let geturl = window.location.href
		// console.log(geturl,'------------网址---------------')
		// 		// http://localhost:8081/#/pages/index/index?qycode=1001&qyname=%E4%BC%81%E4%B8%9A%E5%BF%99
		// 		let getqyinfo = geturl.split('?')[1];////获取后边的字符串
		// 		console.log(getqyinfo,'+++++++++++字符串++++++++++++++')
		// 		let getqys = getqyinfo.split('&')
		// 		console.log(getqys,'*******************')
		// let obj = {}  //创建空对象，接收截取的参数
		// for(let i = 0;i < getqys.length;i++ ){
		//     console.log(i)
		//     let item = getqys[i].split('=')
		//     let key = item[0]
		//     let value = item[1]
		//     obj[key] = value 
		// }
		// 		console.log(obj)
		// 		if (this.obj != null) {
		// 			uni.navigateTo({
		// 				url:"/pages/index/newIndex?id=" + getqyinfo
		// 			})
		// 		}
		// 	}
		// },

		onHide: function() {
			console.log('App Hide');
		},
		methods: {
			// get(){
			// if(window.location.href != ''){
			// 	let geturl = window.location.href
			// 	console.log(geturl,'------------网址---------------')
			// 	// http://localhost:8081/#/pages/index/index?qycode=1001&qyname=%E4%BC%81%E4%B8%9A%E5%BF%99
			// 	let getqyinfo = geturl.split('?')[1];////获取后边的字符串
			// 	console.log(getqyinfo,'+++++++++++字符串++++++++++++++')
			// 	let getqys = getqyinfo.split('&')
			// 	console.log(getqys,'*******************')
			// 	let obj = {}  //创建空对象，接收截取的参数
			// 	for(let i = 0;i < getqys.length;i++ ){
			// 	    console.log(i)
			// 	    let item = getqys[i].split('=')
			// 	    let key = item[0]
			// 	    let value = item[1]
			// 	    obj[key] = value 
			// 	}
			// 	console.log(obj)
			// }
			// },

			setBgGray() {
				this.baGray = uni.requireNativePlugin('Ba-Gray')
				this.$request.api.appDiscoloration({
					appType: 4,
				}).then(resp => {
					if (resp.data.code == 0) {
						this.openGray(0)
					} else {
						this.closeGray()
					}
				})
			},

			openGray(val) { //置灰
				this.baGray.gray({
					grayScale: val //灰度，可不填，默认为0，取值范围0~1，建议值0~0.3
				}, res => {});
			},
			closeGray() { //取消置灰
				this.baGray.ungray(res => {});
			},

			notice(obj) {
				//console.log(uni.getStorageSync('rawData').userId,'88888888888888888888888888asdhfdhfadhfafh------------')
				const userId = uni.getStorageSync('rawData').userId;
				uni.request({
					url: `https://device.jpush.cn/v3/devices/${obj.registrationID}`,
					method: 'POST',
					header: {
						"Authorization": `Basic NzRlNDczN2EzOTMzNzEyMzU5MTI4Njc1OmRiZDZjZWEzOGU4NzA3NzgwNGZkMzM2NA==`,
						"Content-Type": "application/json; charset=utf-8"
					},
					data: {
						// tags:{
						// 	add: [ "tag1",tag2"],
						// 	remove: [ "tag1","tag2"]
						// },
						alias: "JG_" + userId,
						mobile: ""
					},
					success: res => {
						console.log('---推送成功----', JSON.stringify(res))
					}
				})
			},
			//接收消息
			creatSocket: function() {

				console.log("我在app这里连接-*-*-*-*-*-*---*-*");
				let that = this;
				let url = url_config.split("://")[1];
				console.log("url-------", url);
				let a
				if (url == "www.515f.com/api") {
					a = "skt.515f.com"
				} else if (process.env.NODE_ENV == 'development') {
					a = url
				} else {
					//#ifdef H5
					const ipAddress = window.location.href
					const urlObject = new URL(ipAddress)
					a = url.split(":")[0] + ':' + urlObject.port + '/api'
					//#endif
					//#ifdef APP-PLUS
					a = url
					//#endif
				}
				// a="ws://"+a+"/websocket/venus/5/" + uni.getStorageSync('rawData').userId;
				a = "ws://" + a + "/websocket/venus?appType=2&userId=" + uni.getStorageSync('rawData').userId;
				console.log("websocket连接地址", a);
				that.ws = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					url: a,
					success(data) {
						console.log("websocket连接成功");
					},
				});
				that.ws.onOpen((res) => {
					console.log("unapp--WebSocket连接正常打开中...！");
				})
				//监听websocket错误方法
				that.ws.onerror = function(ev) {
					console.log('连接已出错...');
					//延迟执行重连
					setTimeout(() => {
						that.creatSocket();
					}, that.$global.delay);
				};
				//监听websocket关闭方法
				// 这里仅是事件监听【如果socket关闭了会执行】
				that.ws.onClose(() => {
					console.log("已经被关闭了")
				})
				// 注：只有连接正常打开中 ，才能正常收到消息
				that.ws.onMessage((res) => {
					console.log("收到服务器内容：" + res.data);
					var obj = JSON.parse(res.data) //将websocket的string数据转换成对象
					console.log("我接到消息了------------------");
					//接收到消息发信号---首页(为了区分，信号也可以发成getUserList)
					uni.$emit("getOwnerAppRedDotsInfo")
				});
			},
		},
	};
</script>

<style lang="scss">
	@import "uview-ui/index.scss";

	/* 解决头条小程序组件内引入字体不生效的问题 */
	/* #ifdef MP-TOUTIAO */
	@font-face {
		font-family: uniicons;
		src: url('/static/uni.ttf');
	}

	/* #endif */
	@import "uview-ui/index.scss";
	@import "static/css/reset.css";

	body,
	ul,
	li,
	ol,
	h1,
	h2,
	h3,
	h4,
	h5,
	h6,
	p,
	input,
	select,
	textarea,
	dl,
	dd {
		margin: 0;
		padding: 0;
	}

	ul,
	ol {
		list-style: none;
	}

	input,
	select,
	textarea {
		background-color: transparent;
		border: none;
		outline: none;
	}

	textarea {
		resize: none;
	}

	/*右下角的小尾巴*/
	img {
		border: none;
		vertical-align: top;
	}

	a {
		text-decoration: none;
	}

	.clearfix:after,
	.clearfix:before {
		content: "";
		display: table;
	}

	.clearfix:after {
		clear: both;
	}

	/*公用样式*/
	.gWidth {
		width: 1140px;
		margin-left: auto;
		margin-right: auto;
	}

	.fl {
		float: left;
	}

	.fr {
		float: right;
	}

	.norm-single-li {
		// 表单中单排的上下左右通用css边距与布局
		display: flex;
		align-items: center;
		justify-content: space-between;
		// padding: 32rpx 0;
		// margin: 0 32rpx;
		min-height: 84rpx;
		padding: 16rpx 0;

		input {
			text-align: right;
			color: #909399;
			font-size: 14px;
			width: 448rpx;
			text-align: right;
			height: 84rpx;
		}
	}

	.important {
		color: red !important;
	}
</style>